package com.atguigu.lease.web.admin.service.impl;

import com.atguigu.lease.common.contants.RedisConstants;
import com.atguigu.lease.common.jwt.JwtUtil;
import com.atguigu.lease.common.result.ResultCodeEnum;
import com.atguigu.lease.common.springmvc.LeaseException;
import com.atguigu.lease.model.entity.SystemUser;
import com.atguigu.lease.model.enums.BaseStatus;
import com.atguigu.lease.web.admin.service.LoginService;
import com.atguigu.lease.web.admin.service.SystemUserService;
import com.atguigu.lease.web.admin.vo.login.CaptchaVo;
import com.atguigu.lease.web.admin.vo.login.LoginVo;
import com.atguigu.lease.web.admin.vo.system.user.SystemUserInfoVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.wf.captcha.SpecCaptcha;
import com.wf.captcha.base.Captcha;
import io.jsonwebtoken.Claims;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
public class LoginServiceImpl implements LoginService {

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private SystemUserService systemUserService;

    @Override
    public CaptchaVo customSendCode() {
        //生成验证码的图片
        SpecCaptcha specCaptcha = new SpecCaptcha(135,48,4);
        //设置验证码内容的类型
        specCaptcha.setCharType(Captcha.TYPE_DEFAULT);
        //生成验证码图片
        String base64 = specCaptcha.toBase64();
        //正确验证码值
        String code = specCaptcha.text();
        //存到redis中
        //设置字段的key
        String key = RedisConstants.ADMIN_LOGIN_PREFIX + UUID.randomUUID().toString().replaceAll("-","");
        redisTemplate.opsForValue().set(key,code,RedisConstants.ADMIN_LOGIN_CAPTCHA_TTL_SEC, TimeUnit.SECONDS);

        //构造字段的值
        CaptchaVo captchaVo = new CaptchaVo(base64,key);

        return captchaVo;
    }

    @Override
    public String customlogin(LoginVo loginVo) {
        //获取验证码
        String code = (String) redisTemplate.opsForValue().get(loginVo.getCaptchaKey());
        //判断是否过期，为空就是过期了
        if (ObjectUtils.isEmpty(code)) {
            throw new LeaseException(ResultCodeEnum.ADMIN_CAPTCHA_CODE_EXPIRED);
        }
        //判断验证码是否正确
        if (!code.equalsIgnoreCase(loginVo.getCaptchaCode())) {
            throw new LeaseException(ResultCodeEnum.ADMIN_CAPTCHA_CODE_ERROR);
        }
        //判断用户名是否正确
        LambdaQueryWrapper<SystemUser> lambdaQueryWrapper
                = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(SystemUser::getUsername,loginVo.getUsername());
        SystemUser systemUser = systemUserService.getOne(lambdaQueryWrapper);
        if (ObjectUtils.isEmpty(systemUser)) {
            throw new LeaseException(ResultCodeEnum.ADMIN_ACCOUNT_ERROR);
        }
        //判断密码是否正确
        String md5Hex = DigestUtils.md5Hex(loginVo.getPassword());
        if (!systemUser.getPassword().equals(md5Hex)) {
            throw new LeaseException(ResultCodeEnum.ADMIN_ACCOUNT_ERROR);
        }
        //判断用户是否是封禁状态
        if (systemUser.getStatus() == BaseStatus.DISABLE) {
            throw new LeaseException(ResultCodeEnum.ADMIN_ACCOUNT_DISABLED_ERROR);
        }

        String token = JwtUtil.createToken(systemUser.getId(),systemUser.getUsername());
        return token;
    }

    @Override
    public SystemUserInfoVo customInfo(String accessToken) {
        Claims claims = JwtUtil.parseToken(accessToken);
        Integer userId = (Integer) claims.get("userId");
        SystemUser systemUser = systemUserService.getById(userId);

        SystemUserInfoVo systemUserInfoVo = new SystemUserInfoVo();
        systemUserInfoVo.setName(systemUser.getName());
        systemUserInfoVo.setAvatarUrl(systemUser.getAvatarUrl());
        return systemUserInfoVo;
    }


}
